package com.mlog.njyjy.ndop.process.admin.support;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import com.mlog.njyjy.ndop.common.support.DateTimeUtil;
import org.apache.commons.jexl3.JexlBuilder;
import org.apache.commons.jexl3.JexlEngine;
import org.apache.poi.util.IOUtils;
import org.jxls.common.Context;
import org.jxls.expression.JexlExpressionEvaluator;
import org.jxls.transform.Transformer;
import org.jxls.util.JxlsHelper;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 导出excel 并实现自定义函数
 *
 * @author zyz
 */
public class JxlsUtils {

    public static final String TPL_PATH = "tpls/nodeTpl-message.xlsx";

    public static final String PATH_SEPARATOR = "/";

    public static byte[] exportExcel(InputStream is, Map<String, Object> model) {
        //创建临时文件
        try {
            Path path = Files.createTempFile(StrUtil.EMPTY,
                    TPL_PATH.contains(PATH_SEPARATOR) ? TPL_PATH.substring(TPL_PATH.lastIndexOf(PATH_SEPARATOR) + 1) : TPL_PATH);

            File file = path.toFile();
            if (file.exists()) {
                file.setWritable(true);
                OutputStream outputStream = new FileOutputStream(file);
                Context context = new Context();
                if (model != null) {
                    for (String key : model.keySet()) {
                        context.putVar(key, model.get(key));
                    }
                }
                JxlsHelper jxlsHelper = JxlsHelper.getInstance();
                Transformer transformer = jxlsHelper.createTransformer(is, outputStream);

                //获得配置
                JexlExpressionEvaluator evaluator = (JexlExpressionEvaluator) transformer
                        .getTransformationConfig().getExpressionEvaluator();
                //设置静默模式，不报警告
                //evaluator.getJexlEngine().setSilent(true);
                //函数强制，自定义功能
                Map<String, Object> funcs = new HashMap<String, Object>();
                funcs.put("utils", new JxlsUtils());    //添加自定义功能
                JexlBuilder jb = new JexlBuilder();
                jb.namespaces(funcs);
                JexlEngine je = jb.create();
                evaluator.setJexlEngine(je);
                //必须要这个，否则表格函数统计会错乱
                jxlsHelper.setUseFastFormulaProcessor(false).processTemplate(context, transformer);

                IOUtils.closeQuietly(is);
                IOUtils.closeQuietly(outputStream);

                return IoUtil.readBytes(new FileInputStream(file));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new byte[0];
    }

    public String dateFmt(LocalDateTime localDateTime, String pattern) {
        if (localDateTime == null) {
            return "";
        }
        return DateTimeUtil.format(localDateTime, pattern);
    }
}
